import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import NProgress from '@/utils/system/nprogress'
import useDefaultRoute from './hooks/useDefaultRoute'
import { useAsyncRoute } from './hooks/useAsyncRoute'
import { useBeforeEach, useAfterEach } from './hooks/useRouterEach'

const { defaultRoutes, ifDefaultRoute } = useDefaultRoute()
const { getAsyncRoutes } = useAsyncRoute()
const { ifLogin } = useBeforeEach()
const { toCache, toAddTab } = useAfterEach()

// 静态默认路由，包括 [系统路由, 白名单路由]
const BASE_URL = import.meta.env.VITE_BASE_URL
const router = createRouter({
  history: createWebHistory(BASE_URL),
  routes: defaultRoutes,
})

// 前置守卫
router.beforeEach((to, from, next) => {
  console.log('><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<', to)
  NProgress.start()

  if (ifDefaultRoute(to)) {
    if (!ifLogin() && to.path === '/404') {
      next('/login')
    }
    if (ifLogin() && to.path === '/login') {
      next('/')
    }
    next()
    return
  }

  if (ifLogin()) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    console.error('1.请检查token')
    console.error('2.请检查路由', to.path)
    next('/login')
  }
})

// 后置守卫
router.afterEach((to, from, next) => {
  // 1.处理路由缓存
  toCache(to)
  // 2. 添加tab页

  // 不是系统路由和白名单路由，则添加tab标签
  if (!ifDefaultRoute(to)) {
    toAddTab(to)
  }

  NProgress.done()
})

// 添加动态路由
const addMenuRoutes = function (router) {
  if (router.hasRoute('index')) {
    router.removeRoute('index')
  }
  const asyncRoutes = getAsyncRoutes() // 获取动态路由
  router.addRoute(asyncRoutes)
}

export { router, addMenuRoutes }
